﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TBR.Common;
using TBR.Entities;

namespace TBR.Repositories
{
    public class InvitesRepository
    {
        private IList<User> Invites = null;
        private HtmlHelper htmlhelper = null;
        private WebHelper webhelper = null;
        private string HtmlResponse = String.Empty;

        #region constructor
        public InvitesRepository()
        {
            this.webhelper = new WebHelper();
            this.htmlhelper = new HtmlHelper();
            Invites = new List<User>();
        }
        #endregion

        #region events
        public delegate void RequestEventHandler(object source, RequestEventArgs args);
        public class RequestEventArgs : EventArgs
        {
            public IList<User> Invites;
        }
        #endregion

        #region FriendsLoadPageCompleted
        public event RequestEventHandler GetInvitesPageCompleted;
        public void OnGoFriendsPageCompleted()
        {
            if (GetInvitesPageCompleted != null)
            {
                RequestEventArgs args = new RequestEventArgs();
                args.Invites = Invites;
                GetInvitesPageCompleted(this, args);
            }
        }

        private void webhelper_GetInvitesPageCompleted(object sender, TBR.Common.WebHelper.RequestEventArgs args)
        {
            webhelper.RequestCompleted -= webhelper_GetInvitesPageCompleted;
            if (!args.HtmlCode.Contains("Запросов нет"))
            {
                List<string> strUsers = htmlhelper.GetDivCollections(args.HtmlCode, "Вам предлагают дружить", "В меню", "</div></div>", "<div>").ToList();
                Invites = ExtractInvites(strUsers);
            }
            OnGoFriendsPageCompleted();
        }
        private void webhelper_ApproveInviteCompleted(object sender, TBR.Common.WebHelper.RequestEventArgs args)
        {
            webhelper.RequestCompleted -= webhelper_ApproveInviteCompleted;
            GetInvites();
        }
        #endregion

        #region public methods
        public void GetInvites()
        {
            webhelper.RequestCompleted += webhelper_GetInvitesPageCompleted;
            string sid = CookieHelper.GetPropertyCookieByKey("sid");
            Uri uri = new Uri(String.Format("http://tabor.ru/friends/invites.php?sid={0}", sid));
            webhelper.GetHtmlCode(uri, WebHelper.Method.Get);
        }

        public void ApproveInvite(int idUser)
        {
            webhelper.RequestCompleted += webhelper_ApproveInviteCompleted;
            string sid = CookieHelper.GetPropertyCookieByKey("sid");
            Uri uri = new Uri(String.Format("http://tabor.ru/friends/invites.php?confirm={0}&sid={1}", idUser, sid));
            webhelper.GetHtmlCode(uri, WebHelper.Method.Get);
        }
        #endregion

        #region private methods
        private IList<User> ExtractInvites(IList<string> strList)
        {
            List<User> friends = new List<User>();
            foreach (var div in strList)
            {
                var id = GetId(div);
                var friendName = GetName(div);
                var sex = GetSex(div);
                string imgUrl = GetImageUrl(div);
                int age = GetAge(div);
                string location = GetLocation(div);
                string actionDate = GetActionDate(div);
                friends.Add(new User(id, friendName, imgUrl, age, location, sex, actionDate));
            }
            return friends;
        }

        private string GetName(string text)
        {
            text = text.Substring(0, text.IndexOf("</a>"));
            return text.Remove(0, text.LastIndexOf(">") + 1);
        }

        private string GetId(string text)
        {
            text = text.Remove(0, text.IndexOf("id=") + 3);
            return text.Substring(0, text.IndexOf("&amp;"));
        }

        private ESex GetSex(string text)
        {
            return text.IndexOf("boy.png") != -1 ? ESex.Male : ESex.Female;
        }

        private string GetImageUrl(string text)
        {
            string begin = "\"><img src=\"";
            string end = "invites.php";
            text = text.Remove(text.IndexOf(end));
            text = text.Remove(0, text.LastIndexOf(begin) + begin.Length);
            return text.Remove(text.IndexOf('"'));
        }

        private int GetAge(string text)
        {
            try
            {
                string begin = "</a>,";
                text = text.Remove(0, text.IndexOf(begin) + begin.Length);
                return int.Parse(text.Remove(text.IndexOf(" </div>")));
            }
            catch
            {
                return 0;
            }
        }

        private string GetLocation(string text)
        {
            string begin = "/></a></div><div>";
            text = text.Remove(0, text.IndexOf(begin) + begin.Length);
            return text.Remove(text.IndexOf("<"));
        }
        private string GetActionDate(string text)
        {
            int startSpanIndex = text.IndexOf("<span");
            int endSpanIndex = text.IndexOf("span>");
            if (startSpanIndex != -1 && endSpanIndex != -1 && startSpanIndex < endSpanIndex)
            {
                string span = text.Substring(startSpanIndex, endSpanIndex - startSpanIndex);
                int startIndex = span.IndexOf(">") + 1;
                int endIndex = span.LastIndexOf("<");
                return span.Substring(startIndex, endIndex - startIndex);
            }
            else return String.Empty;
        }
        #endregion
    }
}
